package com.studentstreet;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentstreet.adapter.GoodsItemAdapter;
import com.studentstreet.component.AbstractCommonActivity;
import com.studentstreet.component.LoadStateView;
import com.studentstreet.entities.GoodsEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SortBySaleCount;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.GoodsDBHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HangOutActivity extends AbstractCommonActivity implements
		OnItemClickListener {

	// 商品列表控件
	private ListView goodsList;
	// 商品列表适配器
	private GoodsItemAdapter adapter;
	// LoadStateView是一个自写的组件，继承于RelativeLayout，可实现不同状态的布局
	private LoadStateView loadStateView;
	// 商品信息Json数据
	private String goodsJson = "";
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;
	// 商品实体列表
	private List<GoodsEntity> goodsEntityList = null;
	// 排序按钮
	private Button sortButton = null;
	// 回到顶部按钮
	private Button goTopButton = null;
	// 向服务器发送请求的标志
	private String action_flag = "get_rand_goods";
	// 标识发送message的属性。
	private static final int REFRESH_LIST = 0x10001;
	private static final int SHOW_LOAD_STATE_VIEW = 0x10003;
	private static final int HIDE_LOAD_STATE_VIEW = 0x10004;
	private static final int LIST_IS_EMPTY = 0x10005;

	// 用于获得用户数据操作
	PreferenceTools prefTools = null;

	// OEM ++ 3013-04-05 智能推荐
	// 用户名
	private String userName = null;

	// OEM--

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods);
		MyApp.getInstance().addActivity(this);

		Intent intent = getIntent();
		action_flag = (String) intent.getCharSequenceExtra("action");
		// OEM ++ 3013-04-05 智能推荐
		userName = (String) intent.getStringExtra("userName");
		// OEM--

		initUI();

	}

	private void initUI() {
		goodsEntityList = new ArrayList<GoodsEntity>();
		goodsList = (ListView) findViewById(R.id.goodsList);
		adapter = new GoodsItemAdapter(getApplication(), goodsList);
		loadStateView = (LoadStateView) findViewById(R.id.downloadStatusBox);
		titleText = (TextView) findViewById(R.id.title);
		login_bt = (Button) findViewById(R.id.login_bt);
		backImgBt = (ImageButton) findViewById(R.id.header_imgBt);

		setValues();
	}

	private void setValues() {
		// 设置 "重新加载" 监听器
		loadStateView.setOnReloadClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				reload();
			}
		});

		// 返回按钮
		backImgBt.setImageResource(R.drawable.back);
		backImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// 头部中间的标题
		if ("get_rand_goods".equals(action_flag)) {
			titleText.setText(getResources().getString(R.string.more_menu1));
		} else if ("get_recent_goods".equals(action_flag)) {
			titleText.setText(getResources().getString(R.string.more_menu2));
		} else {
			titleText.setText(getResources().getString(R.string.more_menu3));
		}
		// 登录按钮
		login_bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 显示登录对话框
				Intent intent = new Intent(HangOutActivity.this,
						LoginDialog.class);
				startActivity(intent);
			}
		});

		// 设置商品列表的适配器
		goodsList.setAdapter(adapter);
		goodsList.setOnItemClickListener(this);

		// 排序按钮
		sortButton = (Button) findViewById(R.id.goods_sortButton);
		// 返回顶部按钮
		goTopButton = (Button) findViewById(R.id.goods_gotop);

		sortButton.setBackgroundDrawable(null);
		goTopButton.setBackgroundDrawable(null);

		// 加载商品列表
		reload();
	}

	private void reload() {
		// 先清空适配器
		adapter.clean();
		// 开始加载，此时会显示ProgressBar，隐藏 “重新加载” 按钮
		loadStateView.startLoad();
		// 加载列表线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// 使用apache HTTP客户端实现
					String urlStr = Util.BASE_URL + "/servlet/GoodsServlet";
					// 创建网络连接工具对象
					HttpHelper helper = new HttpHelper(urlStr);
					// 添加参数
					// 动作标记
					helper.addParam("action_flag", action_flag);
					// OEM++ 2013-04-05
					helper.addParam("userName", userName);
					// OEM--
					// 获得服务器返回的数据
					goodsJson = helper.getResponse();
					if ("".equals(goodsJson)) {
						sendMessage(LIST_IS_EMPTY);
						return;
					}
					// 让线程休眠，可以看到旋转的ProgressBar
					Thread.sleep(1 * 500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// 将下载的Json数据填充到Adapter中
				loadData();
				// 发送一个消息，通知adapter，列表中的数据有更新
				sendMessage(REFRESH_LIST);
			}
		}).start();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			// 当在订单详情界面将商品添加到收藏夹后，更新本界面相应Item的图标
			RelativeLayout view = (RelativeLayout) goodsList
					.getChildAt(requestCode);
			if (view != null) {
				Button favor = (Button) view
						.findViewById(R.id.goods_add_favorite);
				favor.setBackgroundResource(R.drawable.favorite_s);
			}
		}
	}

	// 将下载的Json数据转化为 GoodsEntity列表，并填充到适配器adapter中
	public void loadData() {
		if ("".equals(goodsJson)) {
			return;// 应从本地数据库读，暂时不实现；
		}
		// 将数据保存到数据库
		GoodsDBHelper dbHelper = new GoodsDBHelper(this);

		dbHelper.saveToDB(goodsJson);
		// 设置adapter
		Type listType = new TypeToken<ArrayList<GoodsEntity>>() {
		}.getType();
		// 创建Gson 对象
		Gson gson = new Gson();
		// 将Json数据转化为List<GoodsEntity>
		goodsEntityList = gson.fromJson(goodsJson, listType);

		// 把商品图片路径补充完整
		for (GoodsEntity goods : goodsEntityList) {
			goods.setImageUrl(Util.BASE_GOODS_IMG_URL + goods.getImageUrl());
		}
		adapter.addGoods(goodsEntityList);
	}

	@Override
	protected void onResume() {
		super.onResume();
		PreferenceTools prefTools = new PreferenceTools(this);
		// 判断是否已经登录
		// 没有登录或者是从 众口味 界面过来的都不改变
		if (!prefTools.isLogin()) {
			return;
		}
		// 登录后修改登录按钮上的text
		String userName = prefTools.getUserName();
		if (!userName.equals("")) {
			login_bt.setText(userName);
			// 去掉登录按钮文本右边的图标
			login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					null);
		}
	}

	@Override
	protected void handleOtherMessage(int flag) {
		switch (flag) {
		case REFRESH_LIST:
			// 更新列表
			adapter.notifyDataSetChanged();
			// 加载完成，让ProgressBar消失
			loadStateView.stopLoad();
			// 如果列表为空，显示提示信息
			if (adapter.getCount() == 0) {
				loadStateView.showEmpty();
			}
			break;
		case SHOW_LOAD_STATE_VIEW:
			loadStateView.startLoad();
			break;
		case HIDE_LOAD_STATE_VIEW:
			loadStateView.stopLoad();
			break;
		case LIST_IS_EMPTY:
			// 让ProgressBar消失
			loadStateView.stopLoad();
			loadStateView.showError();
			break;
		default:
			Toast.makeText(HangOutActivity.this,
					getResources().getString(R.string.network_error),
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	// 商品列表点击事件
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(HangOutActivity.this,
				GoodsDetailActivity.class);
		GoodsEntity goods = goodsEntityList.get(arg2);
		Bundle bundle = new Bundle();
		bundle.putParcelable("goods", goods);
		intent.putExtra("goods_detail", bundle);
		startActivityForResult(intent, arg2);
	}
}
